package cn.skylark.wcm.service.impl;

import cn.skylark.wcm.dao.ResourcesDao;
import cn.skylark.wcm.dao.RoleDao;
import cn.skylark.wcm.dao.RoleResourcesDao;
import cn.skylark.wcm.dao.UserRoleDao;
import cn.skylark.wcm.entity.Resources;
import cn.skylark.wcm.entity.Role;
import cn.skylark.wcm.entity.RoleResources;
import cn.skylark.wcm.entity.UserRole;
import cn.skylark.wcm.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 角色服务实装serviceImpl
 *
 * @author chuhl
 * @since
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleDao roleDao;
    @Autowired
    RoleResourcesDao roleResourcesDao;
    @Autowired
    UserRoleDao userRoleDao;
    @Autowired
    ResourcesDao resourcesDao;
    Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    /**
     * 取得被指定角色列表
     *
     * @param uid Integer
     * @return List<Role>
     */
    @Override
    public List<Role> queryRoleListWithSelected(Integer uid) {
        return roleDao.queryRoleListWithSelected(uid);
    }

    /**
     * 分页获取角色列表
     *
     * @param role   Role
     * @param start  int
     * @param length int
     * @return PageInfo<Role>
     */
    @Override
    public PageInfo<Role> selectByPage(Role role, int start, int length) {
        logger.info("获取所有角色分页查询开始" + "start:" + start + "length:" + length);
        int page = start / length + 1;
        Example example = new Example(Role.class);
        // 分页查询
        PageHelper.startPage(page, length);
        List<Role> rolesList = roleDao.selectByExample(example);
        logger.info("获取所有角色分页查询结束");
        return new PageInfo<>(rolesList);
    }

    /**
     * 删除角色
     *
     * @param roleid Integer
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false,
            rollbackFor = {Exception.class})
    public void delRole(Integer roleid) {
        roleDao.deleteByPrimaryKey(roleid);
        //删除角色资源
        Example example = new Example(RoleResources.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleid", roleid);
        roleResourcesDao.deleteByExample(example);
    }

    /**
     * 保存角色
     *
     * @param role Role 角色实体类
     */
    @Override
    public void save(Role role) {
        role.setDelflg(0);
        role.setType(0);
        roleDao.insert(role);
    }

    /**
     * 根据租户ID获取角色列表
     *
     * @param tennerId 租户id
     * @return
     */
    @Override
    public List<Role> queryRoleListWithTennerId(Integer tennerId) {
        return roleDao.queryRoleListWithTennerId(tennerId);
    }

    /**
     * 删除角色（伦理删除）
     *
     * @param id Integer 角色id
     */
    @Override
    public void deleteRoleById(Integer id) {
        logger.info("倫理刪除角色开始"+"角色id"+id);
        Date now = new Date();
        // 删除角色
        Role role = new Role();
        role.setId(id);
        role.setUpdatetime(now);
        role.setDelflg(1);
        roleDao.updateRole(role);
        //删除角色用户之间的关联
        UserRole userRole = new UserRole();
        userRole.setRoleid(id.toString());
        userRole.setUpdatetime(now);
        userRole.setDelflg(1);
        userRoleDao.updateUserRole(userRole);
        logger.info("倫理刪除角色结束");
    }

    /**
     * 查询角色是否存在
     *
     * @param role 角色的实体类
     * @return
     */
    @Override
    public Role selectByParameter(Role role) {
        logger.info("查询角色是否存在开始"+"role"+role);
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tenanid", role.getTenanid());
        criteria.andEqualTo("roledesc", role.getRoledesc());
        List<Role> roleList = roleDao.selectByExample(example);
        if (roleList.size() > 0) {
            return roleList.get(0);
        }
        logger.info("查询角色是否存在结束");
        return null;
    }

    /**
     * 通过条件获取角色分页列表
     *
     * @param role 角色
     * @param start
     * @param length
     * @return
     */
    @Override
    public PageInfo<Role> selectByPara(Role role,String flag, String searchValue,int start, int length) {
        logger.info("根据租户id获取角色的分页列表开始"+"start:"+start+"length:"+length);
        //总页数
        int page = start / length + 1;
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        //条件查询
        if ("0".equals(flag)){
            if (!StringUtils.isEmpty(searchValue)) {
                criteria.andLike("roledesc", "%" + searchValue + "%");
            }
            if (role.getTenanid()!=null) {
                criteria.andEqualTo("tenanid", role.getTenanid());
            }
        }else if ("1".equals(flag)){
            if (!StringUtils.isEmpty(searchValue)) {
                criteria.andLike("roledesc", "%" + searchValue + "%");
            }
        }
        // 分页查询
        PageHelper.startPage(page, length);
        List<Role> rolesList = roleDao.selectByExample(example);
        logger.info("根据租户id获取角色的分页列表结束");
        return new PageInfo<>(rolesList);
    }

    // }

    /**
     * 根据租户ID获取该租户所有权限
     *
     * @param tenanid Integer 租户id
     * @return
     */
    @Override
    public List<Resources> queryAllResourceWithTenanId(Integer tenanid) {
        logger.info("通过租户id获取所有权限列表开始"+"tenanid"+tenanid);
        //通过tenanid取得租户下所有的角色的id。
        List<Resources> resourcesList = resourcesDao.queryAllResourceWithTenanId(tenanid);
        logger.info("通过租户id获取所有权限列表结束");
        return resourcesList;
    }

}
